package com.zipking.cloud.springbootmybatis.current;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class LogProcessor {
    private final ConcurrentLinkedQueue<String> logQueue = new ConcurrentLinkedQueue<>();
    private final ExecutorService processorPool = Executors.newFixedThreadPool(10);

    public void log(String message) {
        // 生产者线程调用此方法来添加日志到队列
        logQueue.add(message);
    }

    public void startLogProcessing() {
        // 消费者线程池，用于处理队列中的日志
        processorPool.submit(() -> {
            while (true) {
                try {
                    // 消费者线程调用此方法来处理队列中的日志
                    String logEntry = logQueue.poll();
                    if (logEntry != null) {
                        processLog(logEntry);
                    } else {
                        TimeUnit.MILLISECONDS.sleep(100); // 避免 CPU 过载
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });
    }

    private void processLog(String logEntry) {
        // 实际处理日志的逻辑
        System.out.println("Processing log: " + logEntry);
    }

    public static void main(String[] args) {
        LogProcessor logProcessor = new LogProcessor();
        logProcessor.startLogProcessing();

        // 多个生产者线程生成日志
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(() -> {
                logProcessor.log("Log entry " + finalI);
            }).start();
        }
    }

}
